package com.example.smart_video.utils

import android.text.TextUtils
import android.util.Log
import com.example.smart_video.model.Constants.SHARE_PATH
import com.example.smart_video.model.json.PictureData
import com.example.smart_video.model.json.VideoClassData
import com.example.smart_video.ui.fragment.MainFragment
import com.wink_172.library.callback.ICallback
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.CommonUtils
import com.wink_172.library.utils.HttpRequest
import com.wink_172.library.utils.LogUtil
import com.wink_172.library.utils.MMKVTool
import org.xutils.common.Callback
import org.xutils.common.task.Priority
import org.xutils.http.RequestParams
import org.xutils.x
import java.io.File
import java.lang.Exception
import java.util.SortedMap
import java.util.TreeMap


/**基本工具类*/
object HttpUtils {
    private const val TAG = "HttpUtils"

    /**
     * 获取视频列表
     * page 起始值为0
     * classId 分类id
     */
     fun eventGetVideoList(classData:VideoClassData?,callback: ICallback){
        val url = com.example.smart_video.model.Constants.BASE_URL + "video_action/videolist"
        val parameters: SortedMap<String, Any> = TreeMap()
        if (classData != null) {
            parameters["classfyId"] = "" + classData!!.id
        }

        val params = com.example.smart_video.utils.CommonUtils.getTargetRequest(url, parameters)
        x.http().get(params, object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
                Log.e(TAG, "onSuccess: ====>>result:$result")
                MMKVTool.setString(x.app(),
                    com.example.smart_video.model.Constants.LAST_LIST_DATA, result)

                callback.onSendEvent(com.example.smart_video.model.Constants.EventEnum.网络请求成功.ordinal,result)

            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                val last_data = MMKVTool.getString(x.app(),
                    com.example.smart_video.model.Constants.LAST_LIST_DATA, "") as String

                callback.onSendEvent(com.example.smart_video.model.Constants.EventEnum.网络请求成功.ordinal,last_data)

            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {}
        })
    }

    fun updateConfig(content:Boolean,callback:ICallback?) {
        val version_web =
            "http://106.52.115.24:8081/config_action/config_update?id=5&content="+content

        val params = RequestParams(version_web)
        Log.e(TAG, "updateConfig: ====>>" + params.toString())

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
                Log.e(TAG, "updateConfig: ====>>" + result)

//                val configData = JSON.parseObject(
//                    result,
//                    ConfigData::class.java
//                )
                CommonUtils.showToast("updateConfig: ====>>success: " + result)
                if(callback!=null){
                    callback.onSendEvent(Constants.EventEnum.网络请求成功.ordinal)
                }

            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                Log.e(TAG, "updateConfig: ====>>isOnCallback:" + isOnCallback)
                CommonUtils.showToast("updateConfig: ====>>fail" )
                if(callback!=null){
                    callback.onSendEvent(Constants.EventEnum.网络请求错误.ordinal)
                }
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {
            }
        }
        x.http().get(params, commonCallback)


    }
    /**
     * / **
     * * APP急速升级工具
     * * 权限<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"></uses-permission>
     * 下载文件不能包含中文名  英文加下划线+数字可
     * 请注意如果
     * 在onSuccess(File result)  报错
     * 请检查FileProvider
     * 指向本地实际地址
     *
     * local_save_path本地保存绝对路径  /0/storage/download/test.jpg
     *
     * 注意  请不要同一时间下载相同文件--dance分享页就出现过这种问题 org.xutils.ex.FileLockedException: download exists(是下载已存在而不是文件已存在)
     */

    fun downLoadFile(
        web_url: String?,
        local_save_path: String?,
        callback: ICallback
    ) {
//        Log.e(TAG, headSuffix + ": ====>>" + web_url)

        val params = RequestParams(web_url)
        // 为RequestParams设置文件下载后的保存路径
        params.saveFilePath = local_save_path
        params.priority= Priority.BG_LOW//任务的优先级  最低

        params.loadingUpdateMaxTimeSpan=1000//1000ms刷新一下进度

        // 下载完成后自动为文件命名
//        params.setAutoRename(true);
        x.http().get(params, object : Callback.ProgressCallback<File> {
            override fun onSuccess(file: File) {
//                Log.e(TAG, "downLoadFile onSuccess: ====>>" + local_save_path)
                callback.onSendEvent(Constants.EventEnum.网络请求成功.ordinal, local_save_path, file,web_url)
                // 会返回结果,回调方法onActivityResult
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
//                Log.e(TAG, "downLoadFile:onError ====>>" + ex.toString())
                callback.onSendEvent(Constants.EventEnum.网络请求错误.ordinal, local_save_path,web_url)

            }

            override fun onCancelled(cex: Callback.CancelledException) {
                callback.onSendEvent(Constants.EventEnum.网络请求取消.ordinal, local_save_path,web_url)
            }

            override fun onFinished() {
//                Log.e(TAG, "downLoadFile onFinished: ====>>")

                callback.onSendEvent(Constants.EventEnum.网络请求完成.ordinal, local_save_path,web_url)
            }

            override fun onWaiting() {}
            override fun onStarted() {}
            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                // 当前的下载进度和文件总大小和文件地址
                callback.onSendEvent(Constants.EventEnum.下载进度更新.ordinal,  total.toInt(), current.toInt(),web_url)

            }
        })
    }

    /**
     *获取服务器文件夹的所有图片
     */
    fun get_test_imge_list(callback: ICallback?) {

        val params = HttpRequest.getTargetParams("http://106.52.115.24:8888/down/"+SHARE_PATH)
//        params.addBodyParameter("room_id", room_id)

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {

                LogUtil.appendToLog(result)

                val array=result.replace(" ","").
                replace("\n","").
                split("\">下载</a>")
                Log.e(TAG, "array: ====>>"+array.size )
                val flag_path="href=\"/down/"+SHARE_PATH+"?fname="
//                Log.e(TAG, "base url: ====>>http://106.52.115.24:8888/down/Cr07eT3BM94K?fname=testimage/" )

                val image_list:MutableList<PictureData> = ArrayList()
                for (single in array){
                    val start=single.indexOf(flag_path)
                    Log.e(TAG, "start: ====>>"+start+"   all:"+single.length  )
                    if(start==-1){
                        continue
                    }
                    Log.e(TAG, "single====>>: "+single )

                    val ext=if(single.contains(".jpg")){
                        ".jpg"
                    }else if(single.contains(".jpeg")){
                        ".jpeg"
                    }else if(single.contains(".JEPG")){
                        ".JEPG"
                    }else if(single.contains(".JPG")){
                        ".JPG"
                    }else if(single.contains(".PNG")){
                        ".PNG"
                    }else{
                        ".png"
                    }

                    //single.indexOf(ext)//包含多个就会出错
                    val end=single.indexOf(ext)+ext.length
                    Log.e(TAG, "end: ====>>"+end )
                    if(end==-1){
                        continue
                    }

                    val  bbc=single.substring(start,single.length).replace("href=\"","")
                    val picture=PictureData()
                    picture.image_url=bbc
                    picture.other=flag_path
                    image_list.add(picture)

                    Log.e(TAG, "single: ====>>"+bbc )




                }
                callback?.onSendEvent(Constants.EventEnum.网络请求成功.ordinal,image_list)

            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {}
        }
        x.http().get(params, commonCallback)
    }

    fun getConfig(callback:ICallback) {
        val version_web =
            "http://106.52.115.24:8081/config_action/config_detail?id=5"

        val params = RequestParams(version_web)
        Log.e(TAG, "config_detail: ====>>" + params.toString())

        val commonCallback: Callback.CommonCallback<*> = object : Callback.CommonCallback<String> {
            override fun onSuccess(result: String) {
                Log.e(TAG, "config_detail: ====>>" + result)

//                val configData = JSON.parseObject(
//                    result,
//                    ConfigData::class.java
//                )
                if(callback!=null){
                    callback.onSendEvent(Constants.EventEnum.网络请求成功.ordinal,result)
                }

            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
                Log.e(TAG, "config_detail: ====>>isOnCallback:" + isOnCallback)
                if(callback!=null){
                    callback.onSendEvent(Constants.EventEnum.网络请求错误.ordinal)
                }
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {
            }
        }
        x.http().get(params, commonCallback)


    }

}